import {validateNull} from '@/utils/validate'
import website from '@/const/website'

const keyName = website.key + '-'
/**
 * 存储localStorage
 */
export const setStore = (params: any = {}) => {
    let copyParams: { name: any; type: any; content: any } = params;
    copyParams.name = keyName + copyParams.name
    const obj = {
        dataType: typeof (copyParams.content),
        content: copyParams.content,
        type: copyParams.type,
        datetime: new Date().getTime()
    }
    if (copyParams.type) window.sessionStorage.setItem(copyParams.name, JSON.stringify(obj))
    else window.localStorage.setItem(name, JSON.stringify(obj))
}
/**
 * 获取localStorage
 */

export const getStore = (params: any = {}) => {
    let copyParams: { name: any; debug: any } = params;
    copyParams.name = keyName + copyParams.name;
    let content: any;
    let obj = window.sessionStorage.getItem(copyParams.name);

    if (validateNull(obj)) {
        obj = window.localStorage.getItem(copyParams.name);
    } else {
        return;
    }

    try {
        if (obj != null) {
            obj = JSON.parse(obj);
        }
    } catch (e) {
        return obj;
    }

    if (params.debug) {
        return obj;
    }

    // if (typeof obj === "string") {
    //   content = obj.toString();
    // } else if (typeof obj === "number") {
    //     content = Number(obj.toString();)
    // } else if (typeof obj === "boolean") {
    //     content = eval(obj.toString();)
    // } else if (typeof obj === "object") {
    //     content = obj.content
    // }
}
/**
 * 删除localStorage
 */
export const removeStore = (params: any = {}) => {
    let {
        name: string,
        type: boolean
    } = params;
    params.name = keyName + params.name
    if (params.type) {
        window.sessionStorage.removeItem(name)
    } else {
        window.localStorage.removeItem(name)
    }
}

/**
 * 获取全部localStorage
 */
export const getAllStore = (params: any = {}) => {
    const list = []
    const {
        type: boolean
    } = params
    if (params.type) {
        for (let i = 0; i <= window.sessionStorage.length; i++) {
            list.push({
                name: window.sessionStorage.key(i),
                content: getStore({
                    name: window.sessionStorage.key(i),
                    type: 'session'
                })
            })
        }
    } else {
        for (let i = 0; i <= window.localStorage.length; i++) {
            list.push({
                name: window.localStorage.key(i),
                content: getStore({
                    name: window.localStorage.key(i)
                })
            })
        }
    }
    return list
}

/**
 * 清空全部localStorage
 */
export const clearStore = (params: any = {}) => {
    const {type: boolean} = params
    if (params.type) {
        window.sessionStorage.clear()
    } else {
        window.localStorage.clear()
    }
}
